﻿namespace Rzrlf.SP.Innovator.WebParts.CompositeWebPart
{
    public partial class ViewerWebPartUserControl : System.Web.UI.UserControl
    {
        #region Properties...

        private Rzrlf.SP.Innovator.WebParts.IStructureData _data = null;

        public Rzrlf.SP.Innovator.WebParts.IStructureData Data
        {
            get
            {
                return _data;
            }

            set
            {
                _data = value;

                this.LoadGeometry();
            }
        }

        #endregion

        #region Helper Methods...

        private void LoadGeometry()
        {
            if (_data != null && !string.IsNullOrEmpty(_data.CurrentItemXml))
            {
                System.Xml.XPath.XPathDocument xmlDoc = new System.Xml.XPath.XPathDocument(new System.IO.StringReader(_data.CurrentItemXml));

                System.Xml.XPath.XPathNavigator xmlNav = xmlDoc.CreateNavigator();

                System.Xml.XmlNamespaceManager xmlNsMgr = new System.Xml.XmlNamespaceManager(xmlNav.NameTable);
                xmlNsMgr.AddNamespace("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/");

                //string id = xmlNav.SelectSingleNode("//SOAP-ENV:Envelope/SOAP-ENV:Body/Result/Item/id", xmlNsMgr).Value;

                string markup = string.Empty;
                if (xmlNav.SelectSingleNode("//SOAP-ENV:Envelope/SOAP-ENV:Body/Result/Item/markup", xmlNsMgr) != null)
                {
                    markup = xmlNav.SelectSingleNode("//SOAP-ENV:Envelope/SOAP-ENV:Body/Result/Item/markup", xmlNsMgr).Value.Replace("\"", "\\\"").Trim();
                    markup = System.Text.RegularExpressions.Regex.Replace(markup, @"^<!\[CDATA\[", string.Empty);
                    markup = System.Text.RegularExpressions.Regex.Replace(markup, @"\]\]>$", string.Empty);
                }

                string url3d = string.Empty;
                if (xmlNav.SelectSingleNode("//SOAP-ENV:Envelope/SOAP-ENV:Body/Result/Item/url_3d", xmlNsMgr) != null)
                {
                    url3d = xmlNav.SelectSingleNode("//SOAP-ENV:Envelope/SOAP-ENV:Body/Result/Item/url_3d", xmlNsMgr).Value;

                    if (!string.IsNullOrEmpty(url3d))
                    {
                        if (url3d.StartsWith("/"))
                        {
                            url3d = string.Format("{0}{1}", Microsoft.SharePoint.SPContext.Current.Web.Url, url3d);
                        }
                        else
                        {
                            url3d = string.Format("{0}/{1}", Microsoft.SharePoint.SPContext.Current.Web.Url, url3d);
                        }
                    }
                }

                //this.hdnId.Value = id;
                this.hdnMarkup.Value = markup;
                this.hdnUrl3d.Value = url3d;
            }
        }

        #endregion
    }
}
